//index.js
const app = getApp()
const db = wx.cloud.database()
const dayjs = require('../../util/dayjs.min.js')

let requesting = false
Page({
  data: {
    userInfo: null,
    hasLogin: false,
    // 我的选择
    myCheck: 0,
    // 云端-已选择过的
    myCheckCloud: null,
    // 套餐数量
    listCount: 8,
    // 已选总人数
    total: 0,
    // 套餐总数 - 类型合并
    allTypeCheckList: [],
    // 套餐总数
    allCheckList: [],
    // 今日是否有点餐
    todayQueueStatus: true,
    // 是否开启点餐
    taskQueueStatus: true,
    adminList: [],
    // 是否为管理员
    isAdmin: false
  },
  async onPullDownRefresh () {
    await this.getDb_getTaskQueue()
    await this.getDb_getSelect()
    await this.getDb_getSelectById()
    await this.getDb_getAdminList()
    wx.stopPullDownRefresh()
  },
  onShow () {
    // 查询今日数据
    this.getUserInfo()
    requesting = false
  },
  // 进入页面首先获取个人信息
  getUserInfo () {
    let userInfo = wx.getStorageSync('userInfo')
    if (userInfo) {
      this.setUserInfo(userInfo)
      return
    }
    // 获取用户信息
    wx.getSetting({
      success: res => {
        if (res.authSetting['scope.userInfo']) {
          // 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
          wx.getUserInfo({
            success: res => {
              console.log(res)
              this.setUserInfo(res.userInfo)
              wx.setStorageSync('userInfo', res.userInfo)
            }
          })
        }
      }
    })
  },
  setUserInfo (userInfo) {
    this.setData({
      userInfo: userInfo,
      hasLogin: true
    })
    this.getDb_getTaskQueue()
    this.getDb_getSelect()
    this.getDb_getSelectById()
    this.getDb_getAdminList()
  },
  onGetUserInfo (e) {
    if (e.detail.userInfo) {
      this.setData({
        userInfo: e.detail.userInfo,
        hasLogin: true
      })
      this.getDb_getTaskQueue()
      this.getDb_getSelect()
      this.getDb_getSelectById()
      this.getDb_getAdminList()
    }
  },
  // 所有的选择数据，按类型处理
  handleSelect (list) {
    let tempList = []
    for (let i = 0; i < this.data.listCount + 1; i++) {
      tempList[i] = list.filter(nub => nub.type === i) || []
    }
    let allCheckList = list.map(item=>{
      item.formatDate = dayjs(item.date).format('HH:mm:ss')
      return item
    })
    this.setData({
      allTypeCheckList: tempList,
      allCheckList,
      total: list.length
    })
  },
  getDb_getSelect () {
    return new Promise((resolve, reject) => {
      wx.cloud.callFunction({
        name: 'countData',
        data: {
          action: 'get'
        },
        success: res => {
          console.warn('[ countData 云函数] [get] 调用成功：', res)
          this.handleSelect(res.result.data || [])
          resolve()
        },
        fail: err => {
          console.error('[ countData 云函数] [get] 调用失败：', err)
          reject()
        }
      })
    })
  },
  getDb_getSelectById () {
    return new Promise((resolve, reject) => {
      wx.cloud.callFunction({
        name: 'countData',
        data: {
          action: 'getById',
        },
        success: res => {
          console.warn('[ countData 云函数] [getById] 调用成功：', res)
          if (res.result.data.length > 0) {
            this.setData({
              myCheck: res.result.data[0].type,
              myCheckCloud: res.result.data[0].type,
            })
          } else {
            this.setData({
              myCheck: 0,
              myCheckCloud: null,
            })
          }
          resolve()
        },
        fail: err => {
          console.error('[ countData 云函数] [getById] 调用失败：', err)
          reject()
        }
      })
    })
  },
  getDb_getAdminList () {
    return new Promise((resolve, reject) => {
      wx.cloud.callFunction({
        name: 'admin',
        data: {
          action: 'get'
        },
        success: res => {
          console.warn('[ admin 云函数] [get] 调用成功：', res)
          this.setData({
            isAdmin: res.result.data.map(item => item.nickName).includes(this.data.userInfo.nickName)
          })
          resolve()
        },
        fail: err => {
          console.error('[ admin 云函数] [get] 调用失败：', err)
          reject()
        }
      })
    })
  },
  async submitMyCheck () {
    if(!this.data.hasLogin){
      wx.showModal({
        title: '提示',
        content: '请先登录',
        showCancel: false,
        confirmText: '确定',
        confirmColor: '#3CC51F',
      })
      return
    }
    if(requesting){
      return
    }
    requesting = true
    wx.showLoading({
      title: '提交中',
      mask: true
    })
    await this.getDb_getTaskQueue()
    if( !this.data.taskQueueStatus ) {
      wx.showModal({
        title: '提示',
        content: '管理员已关闭订餐，请联系管理员修改或增加选择',
        showCancel: false,
        confirmText: '确定',
        confirmColor: '#3CC51F',
      })
      wx.hideLoading()
      return
    }
    if ( this.data.myCheckCloud === null ) {
      this.getDb_createSelect()
    } else {
      this.getDb_updateSelect()
    }
  },
  getDb_createSelect () {
    wx.cloud.callFunction({
      name: 'countData',
      data: {
        action: 'create',
        type: this.data.myCheck,
        nickName: this.data.userInfo.nickName,
        avatarUrl: this.data.userInfo.avatarUrl,
      },
      success: res => {
        // TODO
        this.getDb_getSelect()
        this.getDb_getSelectById()
        requesting = false
        wx.hideLoading()
        console.warn('[ countData 云函数] [create] 调用成功：', res)
      },
      fail: err => {
        requesting = false
        wx.hideLoading()
        console.error('[ countData 云函数] [create] 调用失败：', err)
      }
    })
  },
  getDb_updateSelect () {
    wx.cloud.callFunction({
      name: 'countData',
      data: {
        action: 'update',
        type: this.data.myCheck,
      },
      success: res => {
        // TODO
        requesting = false
        this.getDb_getSelect()
        this.getDb_getSelectById()
        wx.hideLoading()
        console.warn('[ countData 云函数] [create] 调用成功：', res)
      },
      fail: err => {
        requesting = false
        wx.hideLoading()
        console.error('[ countData 云函数] [create] 调用失败：', err)
      }
    })
  },
  radioClick (e) {
    console.log(e)
    if (!this.data.taskQueueStatus) {
      return
    }
    this.setData({
      myCheck: e.currentTarget.dataset.name
    })
  },
  getDb_createTaskQueue () {
    wx.cloud.callFunction({
      name: 'taskqueue',
      data: {
        action: 'create',
        nickName: this.data.userInfo.nickName,
        remark: '发布新菜谱'
      },
      success: res => {
        this.getUserInfo()
        console.warn('[ taskqueue 云函数] [create] 调用成功：', res)
      },
      fail: err => {
        console.error('[ taskqueue 云函数] [create] 调用失败：', err)
      }
    })
  },
  getDb_switchTaskQueue (e) {
    if(requesting){
      return
    }
    requesting = true
    wx.cloud.callFunction({
      name: 'taskqueue',
      data: {
        action: 'switch',
        nickName: this.data.userInfo.nickName,
        status: e.currentTarget.dataset.status,
        remark: e.currentTarget.dataset.status? '开启点餐': '停止点餐'
      },
      success: res => {
        requesting = false
        this.setData({
          taskQueueStatus: e.currentTarget.dataset.status
        })
        console.warn('[ taskqueue 云函数] [switch] 调用成功：', res)
      },
      fail: err => {
        requesting = false
        console.error('[ taskqueue 云函数] [switch] 调用失败：', err)
      }
    })
  },
  getDb_getTaskQueue () {
    // taskQueueStatus
    return new Promise((resolve, reject) => {
      wx.cloud.callFunction({
        name: 'taskqueue',
        data: {
          action: 'get'
        },
        success: res => {
          console.warn('[ taskqueue 云函数] [get] 调用成功：', res)
          let todayQueueStatus = res.result.data.length > 0
          this.setData({
            todayQueueStatus,
            taskQueueStatus: todayQueueStatus ? res.result.data[0].status : false
          })
          resolve()
        },
        fail: err => {
          console.error('[ taskqueue 云函数] [get] 调用失败：', err)
          reject()
        }
      })
    })
  },

  // 分享方法
  onShareAppMessage: function () {
    return {
      imageUrl: 'https://img.ixiaocong.com/image/activity/0fc13199a0834f80b9f7e163aac14520.jpg',
      title: `今日订餐`,
      path: `/pages/index/index`
    }
  },
})
